//
//  ScanVC.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/11/15.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "ScanVC.h"
#import "TopBackView.h"

#import "RootViewController.h"

#import "PicCollectionViewCell.h"

#import "BigPhotoView.h"

#import "QiniuSDK.h"

#import "ScrollImageViewController.h"


@interface ScanVC ()
<
    UICollectionViewDelegate,
    UICollectionViewDataSource,
    UICollectionViewDelegateFlowLayout,
    UIImagePickerControllerDelegate,
    UINavigationControllerDelegate,
    UITextViewDelegate
>
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UILabel *orderLabel;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *urlArray;//图片数组
@property (nonatomic, strong) NSMutableArray *keyArray;
@property (nonatomic, strong) NSIndexPath *currentIndexPath;
@property (nonatomic, strong) WKProgressHUD *hud;
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, assign) BOOL b;
@property (nonatomic, strong) NSMutableDictionary *dic;
@property (nonatomic, copy) NSString *token;
@property (nonatomic, strong) TopBackView *topBackView;
@end

@implementation ScanVC
#pragma mark -
#pragma mark - Lazy
- (TopBackView *)topBackView {
    if (!_topBackView) {
        _topBackView = [[TopBackView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 64) title:@"事故申报"];
        _topBackView.rightButton.hidden = YES;
        
        [_topBackView.leftButton addTarget:self
                                    action:@selector(backAction)
                          forControlEvents:UIControlEventTouchUpInside];
    }
    return _topBackView;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = WhiteColor;
    
    [self.view addSubview:self.topBackView];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
    _b = NO;

    self.urlArray = @[].mutableCopy;

    self.keyArray = @[].mutableCopy;
    
    self.dic = @{}.mutableCopy;
    
    
    ///加载服务器数据
    [self getDataToServer];
    
}

#pragma mark - 加载服务器数据
- (void)getDataToServer{
    
    NSString *urlString = [NSString stringWithFormat:@"%@accident/%@",Main_interface,self.orderId];
    [Common requestWithUrlString:urlString
                     contentType:application_json
                       errorShow:YES
                        finished:^(id responseObj) {
        
        if ([responseObj[@"data"] isEqual:[NSNull null]]) {
            // 数据为空说明新增
            
            [WKProgressHUD popMessage:responseObj[@"success"] inView:self.view duration:1.5 animated:YES];
            
        } else {
            
            if ([responseObj[@"data"] count] > 0) {
                
                self.dic = responseObj[@"data"];
                
                for (int i = 0; i < [self.dic[@"attachVos"] count]; i++) {
                    
                    NSString *string = [NSString stringWithFormat:@"%@",self.dic[@"attachVos"][i][@"picURL"]];
                    
                    NSURL *url = [NSURL URLWithString:string];
                    [self.urlArray addObject: url];//存储url
                    
                    [self.keyArray addObject:self.dic[@"attachVos"][i][@"picKey"]];
                    
                }
                
            }
            
            [self initSubViews];

            
            [self.collectionView reloadData];

            
        }
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
}

- (void)initSubViews{
    
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight - 64 )];
    self.scrollView.backgroundColor = GrayColor;
    self.scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.scrollView.contentSize = CGSizeMake(screenWidth, screenHeight + 1);
    
    [self.view addSubview:self.scrollView];
    
    
    UIView *firstView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 50 * kHeight)];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(18, 0, 70, 50 * kHeight)];
    [firstView addSubview:label];
    label.text = @"运单号:";
    label.textColor = littleBlackColor;
    label.font = Font(12);
    
    self.orderLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(label.frame), 0, 250, 50 * kHeight)];
    self.orderLabel.text = [NSString stringWithFormat:@"%@",self.dic[@"orderCode"]];
    self.orderLabel.textColor = littleBlackColor;
    self.orderLabel.font = Font(12);
    self.orderLabel.text = self.orderNumber;
    
    [firstView addSubview:self.orderLabel];
    firstView.backgroundColor = WhiteColor;
    [self.scrollView addSubview:firstView];
    
    UILabel *stautsLabel = [[UILabel alloc]initWithFrame:CGRectMake(screenWidth - 150 , 0, 132 , 50 * kHeight)];
    stautsLabel.textColor = YellowColor;
    stautsLabel.textAlignment = NSTextAlignmentRight;
    stautsLabel.font = Font(12);
    if (self.statusId == 0) {
        stautsLabel.text = @"待审核";
    }
    if (self.statusId == 1) {
        stautsLabel.text = @"审核中";
    }
    if (self.statusId == 2) {
        stautsLabel.text = @"审核完成";
    } if (self.statusId == 3) {
        stautsLabel.text = @"审核未通过";
    }

    [firstView addSubview:stautsLabel];
    
    
    
    [self initSecondViewWithString:self.dic[@"description"]];
    
}

- (void)initSecondViewWithString:(NSString *)str{
    UIView *secondView = [[UIView alloc]initWithFrame:CGRectMake(0, 55 * kHeight, screenWidth, 170 * kHeight)];
    secondView.backgroundColor = WhiteColor;
    
    [self.scrollView addSubview:secondView];
    
    self.textView = [[UITextView alloc]initWithFrame:CGRectMake(10 * kHeight, 26 * kHeight, screenWidth - 20 * kWidth, 120 * kHeight)];
    [secondView addSubview:self.textView];
    self.textView.layer.cornerRadius = 5;
    self.textView.layer.borderColor = LineGrayColor.CGColor;
    self.textView.layer.borderWidth = 0.5;
    self.textView.delegate = self;
    self.textView.font = Font(12);
    self.textView.textColor = littleBlackColor;

    self.textView.returnKeyType = UIReturnKeyDone;
    self.textView.text = str;
    if (self.statusId == 1 || self.statusId == 2) {
        
        self.textView.userInteractionEnabled = NO;
    }

    

    [self initCollectionViewWithView:secondView];
    
}

- (void)initCollectionViewWithView:(UIView *)view{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(80 * kHeight, 80 * kHeight);
//    layout.minimumInteritemSpacing = 40 * kHeight;
    layout.sectionInset = UIEdgeInsetsMake(10, 20, 10, 20);

    
      self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(view.frame), screenWidth, 200 * kHeight) collectionViewLayout:layout];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    
    //cell注册
    [self.collectionView registerClass:[PicCollectionViewCell class] forCellWithReuseIdentifier:@"PicCollectionViewCell"];
    [self.scrollView addSubview:self.collectionView];
    self.collectionView.backgroundColor = WhiteColor;
    
    if (self.statusId == 3) {
        
        [self initConfirmButton];

    }

}

- (void)initConfirmButton{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(18 , CGRectGetMaxY(self.collectionView.frame) + 30, screenWidth - 36, Button_height);
    button.backgroundColor = YellowColor;
    [button setTitle:@"确认提交" forState:UIControlStateNormal];
    [button setTitleColor:WhiteColor forState:UIControlStateNormal];
    [button addTarget:self action:@selector(confirmButton) forControlEvents:UIControlEventTouchUpInside];
    button.layer.cornerRadius = 5;
    
    //    self.scrollView.contentSize = CGSizeMake(screenWidth, CGRectGetMaxY(button.frame));
    
    [self.scrollView addSubview:button];
}

- (void)confirmButton{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"是否确认提交" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self postPicture];
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    
    [self presentViewController:alert animated:YES completion:nil];

}

- (void)postPicture{
 
    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:self.keyArray options:NSJSONWritingPrettyPrinted error:nil];
    NSString * jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSDictionary *dic = @{@"waybillId":self.orderId,@"description":self.dic[@"description"],@"picKeys":jsonString,@"id":self.dic[@"id"]};
 
    [[Common shared] afPostRequestWithUrlString:accident_modify parms:dic finishedBlock:^(id responseObj) {
        NSDictionary *dictionay = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        
 
        
        if ([dictionay[@"success"] boolValue]) {
            
            //延迟执行
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self backAction];
                
            });
            
        }
        
    } failedBlock:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];

}

#pragma mark - UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView
     numberOfItemsInSection:(NSInteger)section{
    
    if (self.statusId  != 3) {
        //审核中不能更改
        return self.urlArray.count;
        
        
    } else {
        
        return self.urlArray.count + 1;
        
    }

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PicCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PicCollectionViewCell" forIndexPath:indexPath];
    
    if (self.statusId != 3) {
        //只能展示
    if (self.urlArray.count > 0) {
        
        [cell.heroImageView sd_setImageWithURL:self.urlArray[indexPath.row] placeholderImage:nil options:SDWebImageProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
      
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
//            [self.imgArray addObject:image];
            if (error) {
                cell.heroImageView.image = [UIImage imageNamed:@"bad_picture"];

            }
            
        }];
        
    }else{
        cell.heroImageView.image = [UIImage imageNamed:@"car_add"];
        
    }
    } else {
        
        
        if (self.urlArray.count > 0) {
            if (indexPath.row == self.urlArray.count) {
                cell.heroImageView.image = [UIImage imageNamed:@"car_add"];
            } else {
                
                if ([self.urlArray[indexPath.row] isKindOfClass:[UIImage class]]) {
                    cell.heroImageView.image = self.urlArray[indexPath.row];
                } else {
                    
                    [cell.heroImageView sd_setImageWithURL:self.urlArray[indexPath.row] placeholderImage:nil options:SDWebImageProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                        
                        
                    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                        
                        if (error) {
                            cell.heroImageView.image = [UIImage imageNamed:@"bad_picture"];
                        }
                    }];
                }
            }
        } else {
            cell.heroImageView.image = [UIImage imageNamed:@"car_add"];

        }
        
        
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.statusId != 3) {
//        [WKProgressHUD popMessage:@"审核中或审核通过照片不能修改" inView:self.view duration:1.5 animated:YES];
        
        ScrollImageViewController *scr = [[ScrollImageViewController alloc]init];
        scr.imageArr = self.urlArray;
        
        [self.navigationController pushViewController:scr animated:YES];

    } else {
        _b = YES;
        
        _currentIndexPath = indexPath;
        
        [self photoButton];

    }
 
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(20, 30, 20, 30);
}


#pragma mark 获取照片
- (void)photoButton{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        [weakSelf getPictureFromCamera];
        
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf getPictureFromLibrary];
        
    }];
    
   
    UIAlertAction *action4 = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf deletePicture];
    }];
    
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    
    if (_currentIndexPath.row != self.urlArray.count ){
        
        [alert addAction:action4];

    }
    
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

#pragma mark 拍照
- (void)getPictureFromCamera{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    [self  presentViewController:picker animated:YES completion:nil];
}

#pragma mark 从相册选取
- (void)getPictureFromLibrary{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self  presentViewController:picker animated:YES completion:nil];
    
}

#pragma mark 删除
- (void)deletePicture{
    
    [self.urlArray removeObjectAtIndex:_currentIndexPath.row];
    [self.keyArray removeObjectAtIndex:_currentIndexPath.row];
    
    [self.collectionView reloadData];
    
    
}


#pragma mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        
        PicCollectionViewCell *cell = (PicCollectionViewCell *)[_collectionView cellForItemAtIndexPath:_currentIndexPath];
        cell.heroImageView.image = image;
        
        if (_currentIndexPath.row  != _keyArray.count) {
            
            [self.urlArray replaceObjectAtIndex:_currentIndexPath.row withObject:image];
            
        } else {
            [self.urlArray addObject:image];
        }
        
        self.hud  = [WKProgressHUD showInView:self.view withText:@"" animated:YES];
        
        //上传服务器
        [self getTokenFromQN];
        
    }];
}

#pragma mark 上传七牛
- (NSData *)getImageWith:(UIImage *)image{
    NSData *data = nil;
    if (UIImagePNGRepresentation(image)) {
        
        data = UIImageJPEGRepresentation(image, 0.1);
        
        
    } else {
        data = UIImagePNGRepresentation(image);
        
        
    }
    
    return data;
}

#pragma mark 从七牛获取Token
- (void)getTokenFromQN{
    
    [Common requestWithUrlString:qiniu_token contentType:application_json errorShow:YES finished:^(id responseObj) {
        if ([responseObj[@"success"] boolValue]) {
            
            self.token = responseObj[@"data"];
            
            PicCollectionViewCell *cell = (PicCollectionViewCell *)[_collectionView cellForItemAtIndexPath:_currentIndexPath];
            
            [self uploadImageToQNWithData:[self getImageWith:cell.heroImageView.image]];
            
            
        }
    } failed:^(NSString *errorMsg) {
        
        
        NSLog(@"%@",errorMsg);
    }];
    
    
    
}

- (void)uploadImageToQNWithData:(NSData *)data{
    
    QNUploadManager *upManager = [[QNUploadManager alloc]init];
    
    QNUploadOption *uploadOption = [[QNUploadOption alloc]initWithMime:nil progressHandler:^(NSString *key, float percent) {
        
    } params:nil checkCrc:NO cancellationSignal:nil];
    
    [upManager putData:data key:nil token:self.token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
        
        if (_currentIndexPath.row  !=  _keyArray.count ) {
            //替换
            [self.keyArray replaceObjectAtIndex:_currentIndexPath.row withObject:resp[@"key"]];
            
        } else {
            //添加
            [self.keyArray addObject:resp[@"key"]];
            
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.collectionView reloadData];
            
        });
        
        [self.hud dismiss:YES];
        
    } option:uploadOption];
}

#pragma mark UITextViewDelegate
- (BOOL)textView:(UITextView *)textView
shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ( [ @"\n" isEqualToString: text])
    {
        [textView resignFirstResponder];
        
        return  NO;
    }
    else
    {
        return YES;
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES];
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:YES];
}

- (void)backAction{
    if (self.isChange) {
        self.isChange(_b);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}









@end
